class ContactsController < ApplicationController
  before_filter :login_required, :find_project
   
  def index
    #@inhouse_contacts = @project ? Contact.find_all_inhouse(@project.id) : Contact.find_all_inhouse
    @contacts = @project ? @project.contacts : Contact.find(:all)
  end

  def new
    @contact = Contact.new
    @contacts = Contact.find(:all, :order => 'name ASC', :include => [:project])
  end
  
  def create
    @contact = Contact.new(params[:contact].merge(:project_id => params[:project_id]))
    capitalize_contact(@contact.attributes)
    
    # Set company if inhouse checkbox is selected (in the case when jscript not supported)
    if params[:contact]['inhouse'] == "1"
      @contact.company = "Inhouse Personnel"
    end
    
    if @contact.save
      flash[:notice] = 'Contact successfully saved'
      redirect_to :action => :index
    else
      @contacts = Contact.find(:all, :order => 'name ASC', :include => [:project])
      render :action => :new
    end
  end
  
  
  def show
    @contact = Contact.find(params[:id]) 
  end
 
 def destroy
   @contact = Contact.find(params[:id])
   if @contact.destroy
    flash[:notice] = 'Contact successfully deleted'
   end
   redirect_to :back
 end
 
 def edit
  @contact = Contact.find(params[:id])
  session[:prev_page] = request.env["HTTP_REFERER"] 
  @prev_page =  session[:prev_page].to_s
 end
 
 def update
  @contact = Contact.find(params[:id])
  capitalize_contact(params[:contact])
  
  # Empty company if inhouse checkbox is selected (in the case when jscript not supported)
  if params[:contact]['inhouse'] == "1"
      params[:contact]['company'] = "Inhouse Personnel"
  end  
    
  if @contact.update_attributes(params[:contact])
    flash[:notice] = 'Contact successfully updated'
    redirect_to session[:prev_page].to_s
  else
    @prev_page = session[:prev_page]
    render :action => :edit  
  end
 end
 
 def list
   @contacts = @project ? @project.contacts : Contact.find(:all)
 end
 
 private
 def find_project
   @project = Project.find_by_id(params[:project_id])
 end
 
 # Capitalize first letter of name, surname, company, address and profession for contact
 private
 def capitalize_contact(contact_attrs) 
  contact_attrs['name'].capitalize!
  contact_attrs['surname'].capitalize!
  contact_attrs['company'].capitalize! unless contact_attrs['company'].nil?
  contact_attrs['address'].capitalize!
  contact_attrs['profession'].capitalize!
 end
end
